﻿#pragma once

#include "land_base_conf.h"

#ifdef LAND_WINDOWS
#include <Windows.h>
#else
    #define _XOPEN_SOURCE 500
    #include <pthread.h>
    #include <unistd.h>

     #ifndef pthread_spinlock_t
         #define pthread_spinlock_t      pthread_mutex_t
         #define pthread_spin_init(l, v)    pthread_mutex_init(l, NULL)
         #define pthread_spin_lock(l)    pthread_mutex_lock(l)
         #define pthread_spin_trylock(l) pthread_mutex_trylock(l)
         #define pthread_spin_unlock(l)  pthread_mutex_unlock(l)
         #define pthread_spin_destroy(l) pthread_mutex_destroy(l)
     #endif
#endif


#ifdef LAND_WINDOWS
typedef DWORD LandThread;
#else
typedef pthread_t LandThread;
#endif


typedef struct{
#ifdef LAND_WINDOWS
    BOOL lock;
#else
    pthread_spinlock_t  lock;
#endif
}LandSpinLock;

typedef struct{
#ifdef LAND_WINDOWS
    CRITICAL_SECTION lock;
#else
    pthread_mutex_t lock;
#endif
}LandMutex;

typedef struct {
#ifdef LAND_WINDOWS
    SRWLOCK lock;
#else
    pthread_rwlock_t lock;
#endif
}LandRWLock;

typedef struct {
#ifdef LAND_WINDOWS
	// HAND evt;
    CONDITION_VARIABLE cond;
    CRITICAL_SECTION lock;
#else
    pthread_mutex_t lock;
    pthread_cond_t cond;
#endif
}LandCond;

LAND_BASE_API int
landNewThread (LandThread * t,
	void *(*start_fn)(void *), void * arg, int detach);

LAND_BASE_API void
landExitBaseThread ();

LAND_BASE_API int
landCancelthread (LandThread t);

LAND_BASE_API int
landJoinThread (LandThread t);

LAND_BASE_API LandThread
landSelfThread ();

LAND_BASE_API void
landSleep(uint32_t ms);


LAND_BASE_API void
landInitBaseSpin(LandSpinLock * l);

LAND_BASE_API void
landClearSpin(LandSpinLock * l);

LAND_BASE_API int
landLockSpin(LandSpinLock * l);

LAND_BASE_API int
landTryLockSpin(LandSpinLock * l);

LAND_BASE_API int
landUnlockSpin(LandSpinLock * l);


LAND_BASE_API void
landInitBaseMutex(LandMutex * l);

LAND_BASE_API int
landLockMutex(LandMutex * l);

LAND_BASE_API int
landTryLockMutex(LandMutex * l);

LAND_BASE_API int
landUnlockMutex(LandMutex * l);

LAND_BASE_API void
landClearMutex(LandMutex * l);


LAND_BASE_API void
landInitBaseRWLock (LandRWLock * l);

LAND_BASE_API void
landClearRWLock(LandRWLock * l);

LAND_BASE_API void
landLockRWLockR (LandRWLock * l);

LAND_BASE_API void
landLockRWLockW (LandRWLock * l);

LAND_BASE_API void
landUnlockRWLockR (LandRWLock * l);

LAND_BASE_API void
landUnlockRWLockW (LandRWLock * l);


LAND_BASE_API void
landInitBaseCond (LandCond * cond);

LAND_BASE_API void
landClearCond (LandCond * cond);

LAND_BASE_API int
landLockCond (LandCond * cond);

LAND_BASE_API int
landTryLockCond (LandCond * cond);

LAND_BASE_API int
landUnlockCond (LandCond * cond);

LAND_BASE_API int
landWaitCond (LandCond * cond);

LAND_BASE_API int
landWaitCondTimeout (LandCond * cond, uint32_t ms);

LAND_BASE_API int
landSignalCond (LandCond * cond);

LAND_BASE_API int
landBroadcastCond (LandCond * cond);

